/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef } from 'react';
import { message, Button, Space } from 'antd';
import ProCard from '@ant-design/pro-card';
import { getDbName, showProcessList, killProcess, querySql } from '@/services/tools/newSql';
import KbDescriptions from '@/components/KbDescriptions';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { TableColumns } from '@/components/_pages/tools/newSql/_utils/type';
import type { ConnectState } from '@/models/connect';
import {
  descriptionsMap,
  newSqlColumns,
  processList,
} from '@/components/_pages/tools/newSql/_utils/index.config';
import { useSelector } from 'umi';
import ProForm, { ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';

const Index = () => {
  const formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();
  const descriptionRef = useRef<any>();
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const [dbName, setDbName] = useState<string | undefined>(undefined);
  const [sql, setSql] = useState<string>('');
  const [showType, setShowType] = useState<'Table' | 'Descriptions' | ''>('');
  const [loading, setLoading] = useState<boolean>(false);

  const getTableList = (params: any) => {
    setLoading(true);
    return showProcessList(params).then((res) => {
      setLoading(false);
      const { code, data, msg } = res;
      if (code === 0) {
        return {
          data,
        };
      } else {
        message.error(msg);
        return [];
      }
    });
  };

  const onKill = async (id: string) => {
    killProcess({ dbName, id }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success(msg);
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };
  const onSearch = async (params: any) => {
    setDbName(params.db);
    setShowType('Table');
    actionRef.current?.reload();
  };
  const onFinish = async (params: any) => {
    formRef.current?.validateFields().then((values) => {
      if (processList.includes(params.sql)) {
        setShowType('Table');
        formRef.current?.submit();
        return;
      }
      setDbName(values.db);
      setSql(params.sql);
      setShowType('Descriptions');
      descriptionRef.current?.reload();
    });
  };
  const onQuerySql = async (params: any) => {
    return querySql(params).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        return { data };
      } else {
        message.error(msg);
        return {};
      }
    });
  };

  const columns: ProColumns<TableColumns>[] = [
    ...newSqlColumns,
    {
      title: '操作',
      dataIndex: 'operate',
      valueType: 'option',
      align: 'center',
      width: winSize === 'xs' ? 50 : 100,
      fixed: 'right',
      render: (_, record) => {
        return (
          <Button type='primary' size='small' onClick={onKill.bind(null, record.Id)}>
            kill
          </Button>
        );
      },
    },
  ];

  return (
    <PageContainer className={styles.main}>
      <ProCard>
        <Space direction='vertical' size={20} style={{ width: '100%' }}>
          <ProForm
            layout={winSize === 'xs' ? 'vertical' : 'inline'}
            formRef={formRef}
            onFinish={onSearch}
            submitter={{
              render: ({ form }) => [
                <Button
                  type='primary'
                  key='form_submit'
                  loading={loading}
                  onClick={() => form?.submit()}
                >
                  show processlist
                </Button>,
              ],
            }}
          >
            <ProFormSelect
              showSearch
              name='db'
              width='sm'
              request={getDbName}
              rules={[{ required: true, message: '请选择数据库' }]}
              placeholder='搜索数据库'
            />
          </ProForm>
          <ProForm
            className={styles.main_runSql}
            layout='vertical'
            onFinish={onFinish}
            submitter={{
              searchConfig: {
                resetText: false,
                submitText: '执行',
              },
            }}
          >
            <ProFormTextArea
              name='sql'
              rules={[{ required: true, message: '请输入命令语句' }]}
              placeholder='输入命令语句'
            />
          </ProForm>
          {showType === 'Table' ? (
            <DragTable>
              <ProTable
                rowKey='id'
                actionRef={actionRef}
                request={getTableList}
                pagination={false}
                params={{ dbName }}
                columns={columns}
                scroll={{ x: 1200 }}
                options={false}
                search={false}
              />
            </DragTable>
          ) : showType === 'Descriptions' ? (
            <KbDescriptions
              actionRef={descriptionRef}
              layout='horizontal'
              column={1}
              loading
              request={onQuerySql}
              params={{ sql, dbName }}
              columns={descriptionsMap}
              debounceTime={300}
            />
          ) : null}
        </Space>
      </ProCard>
    </PageContainer>
  );
};

export default Index;
